<?php

namespace App\Services\MakeGoldRecord;

use App\Models\User;
use Carbon\Carbon;
use App\Models\GoldRound;
use App\Models\GoldProduct;
use App\Http\Controllers\Api\V1\Requests\FormRequest;

class MakeGoldRecordRequest extends FormRequest
{
	public function rules()
	{
		return [
			'pid' => [
				'required',
				'integer',
				'min:1',
				$this->goldProduct(),
			],
			'rid' => [
				'required',
				'integer',
				'min:1',
			],
		];
	}

	public function goldProduct()
	{
		return function ($key, $value, $fail) {

			$pid = $this->pid;
			$rid = $this->rid;
			$time = Carbon::now();

			if (!GoldProduct::sIsInCache($pid, $rid)) {
				return $fail('抢购商品不存在');
			} elseif (GoldProduct::sIsInSoldCache($pid, $rid)) {
				return $fail('当前商品已抢光');
			} elseif ($time->lt(GoldRound::todayOpenedAt($rid))) {
				return $fail('本场尚未开场');
			} elseif ($time->lt(GoldRound::todayStartedAt($rid))) {
				return $fail('本场尚未开始');
			} elseif ($time->gt(GoldRound::todayEndedAt($rid))) {
				return $fail('本场已经结束');
			} elseif (GoldRound::isCacheEnd($rid)) {
				return $fail('本场暂未开放');
			/*} elseif (! $this->isGoldCashesEnough()) {
                return $fail('抢购金不足');*/
            } elseif (! $this->isGoldBeansEnough()) {
				return $fail('金豆不足请联系小二充值');
			} elseif ($this->isUserRecord()) {
				return $fail('不可抢购自己的寄卖商品');
			}

			return true;
		};
	}

	/*protected function isGoldCashesEnough(): bool
	{
        
        $user = $this->user();
		$item = GoldProduct::sGetCache($this->pid, $this->rid);
		return $user->isGoldCashesEnough($item['cash_price_today']);
	}
*/
	protected function isGoldBeansEnough(): bool
	{
        /**
         * @var User $user
         */
        $user = $this->user();
		$item = GoldProduct::sGetCache($this->pid, $this->rid);
		return $user->isGoldBeansEnough($item['gold_beans_today']);
	}

	protected function isUserRecord(): bool
	{
        /**
         * @var User $user
         */
        $user = $this->user();
		$item = GoldProduct::sGetCache($this->pid, $this->rid);
		return $item['resell_user_id']  == $user->id ? true : false ;
	}
}
